import os
import sys

import portalocker
import yaml
from loguru import logger


class Config:

    config_file = "config.yml"

    def __init__(self, config_path=r''):
        if config_path == r'':
            self.config_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            self.config_path = os.path.join(self.config_dir, self.config_file)
        else:
            self.config_path = config_path
        logger.debug("config file: {}".format(self.config_path))

    def read_config(self):
        config_file = open(self.config_path, 'r', encoding='utf-8')
        config_content = yaml.load(config_file, Loader=yaml.FullLoader)
        logger.debug("read config file: {}", self.config_path)
        config_file.close()
        return config_content

    # 修改完的yaml文件写入config.yml
    def write_config(self, content):
        with open(self.config_path, 'w', encoding='utf-8') as config_file:
            portalocker.lock(config_file, portalocker.LOCK_EX)
            yaml.dump(content, config_file)
            # fcntl.flock(config_file.fileno(), fcntl.LOCK_UN)
        logger.debug("write config file: {}", self.config_path)
        # config_file = open(self.config_path, 'w', encoding='utf-8')
        # yaml.dump(content, config_file)
        # config_file.close()
